# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Security::Ingestion::Tasks::IngestVulnerabilityFlags, feature_category: :vulnerability_management do
  describe '#execute' do
    let_it_be(:pipeline) { create(:ci_pipeline) }

    let_it_be(:vulnerability_finding) { create(:vulnerabilities_finding) }
    let_it_be(:existing_vulnerability_flag_1) { create(:vulnerabilities_flag, origin: 'post analyzer 1', finding: vulnerability_finding) }
    let_it_be(:existing_vulnerability_flag_2) { create(:vulnerabilities_flag, origin: 'post analyzer 2', finding: vulnerability_finding, description: 'foo') }
    let_it_be(:existing_vulnerability_flag_3) { create(:vulnerabilities_flag, origin: 'post analyzer 3', finding: vulnerability_finding, description: 'zoo') }

    let(:long_description) { 'a' * 1001 }
    let(:report_finding_flag_2) { create(:ci_reports_security_flag, origin: 'post analyzer 2', description: 'bar') }
    let(:report_finding_flag_3) { create(:ci_reports_security_flag, origin: 'post analyzer 3', description: long_description) }
    let(:report_finding_flag_4) { create(:ci_reports_security_flag, origin: 'post analyzer 4') }
    let(:report_finding_flag_5) { create(:ci_reports_security_flag, origin: 'post analyzer 5') }

    let(:report_finding) { create(:ci_reports_security_finding, flags: [report_finding_flag_2, report_finding_flag_3, report_finding_flag_4, report_finding_flag_5]) }
    let(:finding_map) { create(:finding_map, finding: vulnerability_finding, report_finding: report_finding) }
    let(:service_object) { described_class.new(pipeline, [finding_map]) }

    subject(:ingest_vulnerability_flags) { service_object.execute }

    it 'creates new records and updates the existing ones' do
      expect { ingest_vulnerability_flags }.to change { vulnerability_finding.vulnerability_flags.count }.from(3).to(4)
                                           .and change { existing_vulnerability_flag_2.reload.description }.from('foo').to('bar')
                                           .and change { existing_vulnerability_flag_3.reload.description }.from('zoo').to(long_description.truncate(1000))
    end

    it 'deletes the old records' do
      expect { ingest_vulnerability_flags }.to change { Vulnerabilities::Flag.find_by_id(existing_vulnerability_flag_1.id) }.to(nil)
    end

    it_behaves_like 'bulk insertable task'
  end
end
